/*
 * test.c
 *
 *  Created on: Aug 5, 2019
 *      Author: duan
 */

#include "xutil.h"
#include "xintc.h"
#include "xuartlite.h"
#include "xuartlite_l.h"
#include "serial.h"

XUartLite RS232_Uart;

UART_T uart = { .fetch_count = 0, .receive_count = 0, .send_byte = XUartLite_Putc };

void XUartLite_Putc(unsigned char data) {
	XUartLite_Out32(XPAR_RS232_UART_BASEADDR + XUL_TX_FIFO_OFFSET, (u32)(data));
}

void uart_rev_handler(void) {
	while (!XUartLite_IsReceiveEmpty(XPAR_RS232_UART_BASEADDR)) {
		uart.receive_buffer[uart.receive_count] = XUartLite_RecvByte(XPAR_RS232_UART_BASEADDR);
		uart.receive_count++;
		if (uart.receive_count == BUF_SIZE)
			uart.receive_count = 0; //loop buffer
	}
}

void serial_init() {

	XUartLite_Initialize(&RS232_Uart, XPAR_RS232_DEVICE_ID);
	XUartLite_EnableInterrupt(&RS232_Uart);
	microblaze_enable_interrupts();

	XIntc_RegisterHandler(XPAR_INTC_0_BASEADDR,
			XPAR_AXI_INTC_0_RS232_INTERRUPT_INTR,
			(XInterruptHandler) uart_rev_handler, (void *) 0);

	XIntc_MasterEnable(XPAR_INTC_0_BASEADDR);
	XIntc_EnableIntr(XPAR_INTC_0_BASEADDR, XPAR_RS232_INTERRUPT_MASK);

	xil_printf("--- serial init ok ---\r\n");
}
